package core;

import objects.Robot;


/**
 * A class containing a command for a Robot, for example to move a given distance forward.
 * 
 * @author ruben.ortlam
 */
public class Command {
	private int type;
	private int param;
	private Robot robot;
	
	private boolean finished;
	
	private double var;
	
	/**
	 * Creates a new Command with the given parameters.
	 * 
	 * @param type The type of the command.
	 * @param param The parameter of the command.
	 * @param robot The robot that should execute the commands.
	 */
	public Command(int type, int param, Robot robot) {
		this.type = type;
		this.param = param;
		this.robot = robot;
		switch(type) {
		case 4:
			this.var = robot.getTurretAngle();
			break;
		default:
			this.var = 0.0;
			break;
		}
	}
	
	/**
	 * Executes the command in the current tick.
	 */
	public void run() {
		if(!finished) {
			double tmp = Math.toRadians(param);
			
			switch(type) {
			case 1:
//				System.out.println(var + ":" + tmp + ":" + robot.getAngle());
				if(var < tmp - Robot.ANGSPEED && !finished) {
					var += Robot.ANGSPEED;
					robot.turnRight();
				} else if(var > tmp + Robot.ANGSPEED && !finished) {
					var -= Robot.ANGSPEED;
					robot.turnLeft();
				} else {
					finished = true;
				}
				if(Main.SOUND_ACTIVE && !robot.engineSound.isPlaying()) {
					robot.engineSound.play();
				}
				break;
			case 2:
				if(param > 0) {
					if(var < param && !finished) {
						var += Robot.SPEED;
						robot.moveForward();
						if(Main.SOUND_ACTIVE && !robot.engineSound.isPlaying()) {
							robot.engineSound.play();
						}
					} else {
						finished = true;
					}
				} else if(param < 0) {
					if(var > param && !finished) {
						var -= Robot.SPEED;
						robot.moveBackward();
						if(Main.SOUND_ACTIVE && !robot.engineSound.isPlaying()) {
							robot.engineSound.play();
						}
					} else {
						finished = true;
					}
				} else {
					finished = true;
				}
				break;
			case 3:
				robot.fire();
				finished = true;
				break;
			case 4:
//				System.out.println(var + ":" + tmp + ":" + robot.getTurretAngle());
				if(robot.getTurretAngle() < tmp - Robot.ANGSPEED && !finished) {
					robot.turnTurretRight();
				} else if(robot.getTurretAngle() > tmp + Robot.ANGSPEED && !finished) {
					robot.turnTurretLeft();
				} else {
					robot.setTurretAngle(tmp);
					finished = true;
				}
				break;
			case 5:
				robot.placeMine();
				finished = true;
				break;
			default:
				finished = true;
				break;
			}
		}
	}
	
	/**
	 * Returns if the command has finished.
	 * 
	 * @return true if the command has finished, false otherwise
	 */
	public boolean isFinished() {
		return finished;
	}

	public int getType() {
		return type;
	}

	public void setFinished(boolean finished) {
		this.finished = finished;
	}
}
